﻿using System.Text.RegularExpressions;
using System.Windows.Controls;

namespace ICodeShare.UI.Controls.ValidationRules
{
    /// <summary>
    /// 绑定数据验证规则，手机号码验证
    /// </summary>
    /// <example>
    /// 1.在xmal文件引用DateConverter类所在命名空间。
    ///    xmlns:vals="http://schemas.extended.wpf.com/validations"
    /// 2.在xaml文件中指定Binding值的Converter
    ///  <TextBox.Text>
    ///      <Binding Path="MobilePhone" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
    ///          <Binding.ValidationRules>
    ///              <vals:MobilePhoneRule/>
    ///           </Binding.ValidationRules>
    ///      </Binding>
    ///   </TextBox.Text>
    /// </example>
    public class MobilePhoneRule : ValidationRule
    {
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            string mobilePhone = value as string;

            if (!string.IsNullOrWhiteSpace(mobilePhone))
            {
                string mobilePhoneFormartRegex = @"^[1]([3][0-9]{1}|59|58|88|89)[0-9]{8}$";

                // 检查输入的字符串是否符合手机号码格式
                if (!Regex.IsMatch(mobilePhone, mobilePhoneFormartRegex))
                {
                    return new ValidationResult(false, "手机号码格式不正确");
                }
            }
            return new ValidationResult(true, null);
        }
    }
}